package com.mzj.eagle.jobs.heartbeat.service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.mzj.eagle.jobs.heartbeat.entity.Heartbeat;
import com.mzj.eagle.jobs.heartbeat.entity.HeartbeatEmqEs;
import com.mzj.eagle.jobs.heartbeat.repository.HeartbeatEsRepository;

@Transactional
@Service
public class HeartbeatService {

	private static final Logger LOG = LoggerFactory.getLogger(HeartbeatService.class);
	@Value("${scale.heartbeat.list.size}")
	private Integer heartbeatListSize;

	private static String MACHINE_KEY = "SCALE_MACHINES";

	//@Autowired
	//private HeartbeatSolrRepository heartbeatSolrRepository;

	@Autowired
	private HeartbeatEsRepository heartbeatEsRepository;

	private List<Heartbeat> list;

	public boolean insertData(String msg) throws IOException {
		LOG.info("msg:" + msg);
		Heartbeat heartbeat = isHeartbeatJson(msg);
		if(heartbeat == null) {
			return true; //不是JSON数据丢掉
		}
		int useType = 0;
		heartbeat.setUseType(useType);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String time = "";
		if (heartbeat.getReqTime() != null) {
			time = sdf.format(heartbeat.getReqTime());
		} else {
			time = sdf.format(new Date());
		}
		Date heartbeatTime = null;
		try {
			heartbeatTime = sdf.parse(time.substring(0, time.length() - 1) + "0");
		} catch (ParseException e) {
			LOG.error(e.getMessage(), e);
		}
		heartbeat.setHeartbeatTime(heartbeatTime);
		save(heartbeat);
		LOG.info(JSON.toJSONString(heartbeat));
		return true;
	}
	
	public Heartbeat isHeartbeatJson(String msg) {
		try {
			return JSON.parseObject(msg, Heartbeat.class);
		}catch(Exception e) {
			LOG.error("MQ message error:"+e.getMessage()+" msg:"+msg, e);
			return null;
		}
	}

	private Heartbeat save(Heartbeat heartbeat) {
		heartbeat.setId(UUID.randomUUID().toString().replace("-", ""));
		if (!StringUtils.isEmpty(heartbeat.getMachineId())) {
			if (list == null) {
				list = new ArrayList<Heartbeat>();
			}
			list.add(heartbeat);

		}
		if(heartbeatListSize==null||heartbeatListSize<0) {
			heartbeatListSize=100;
		}
		if (list!=null && list.size() >= heartbeatListSize) {
			// heartbeatInsert(list);
			try {
				// createIndexResponse("scale_hb", "scale_hb", list);
				heartbeatSave(list);
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
			}
			list = new ArrayList<Heartbeat>();

		}
		return heartbeat;
	}
	
	public boolean heartbeatSave() {
		if(list!=null&&list.size()<heartbeatListSize) {
			return heartbeatSave(list);
		}
		return true;
	}
	
	public void save(HeartbeatEmqEs t) {
		this.heartbeatEsRepository.save(t);
	}

	public boolean heartbeatSave(List<Heartbeat> list) {
		if(list==null||list.size()<=0) {
			return true;
		}
		boolean falg = false;
		List<HeartbeatEmqEs> listEs = new ArrayList<HeartbeatEmqEs>();
		SimpleDateFormat sdfs = new SimpleDateFormat("yyyyMMddHHmmss");
		for (Heartbeat hb : list) {
			HeartbeatEmqEs solr = new HeartbeatEmqEs();
//			GetId.getId()
//			solr.setId(hb.getId());
			solr.setAppStatus(hb.getAppStatus());
			solr.setScaleClose(hb.getClose());
			if(hb.getHeartbeatTime()!=null) {
				solr.setHeartbeatTime(sdfs.format(hb.getHeartbeatTime()));
			}
			solr.setLatitude(hb.getLatitude());
			solr.setLongitude(hb.getLongitude());
			solr.setScaleId(hb.getMachineId());
			solr.setSign(hb.getSign());
			solr.setStatus(hb.getStatus());
			solr.setVersion(hb.getVersion());
			solr.setApkVersion(hb.getVersion());
			solr.setAppStatus(hb.getAppStatus());
			solr.setUseType(hb.getUseType());
			if(hb.getReqTime()!=null) {
				solr.setReqTime(sdfs.format(hb.getReqTime()));
			}
			if(hb.getReceiverTime()!=null) {
				solr.setReceiverTime(sdfs.format(hb.getReceiverTime()));
			}else {
				solr.setReceiverTime(sdfs.format(new Date()));
			}
			if (hb.getScaleMachineVo() != null) {
				solr.setApkMasterVersion(hb.getScaleMachineVo().getApkMasterVersion());
				if(hb.getScaleMachineVo().getCreateTime()!=null){
					solr.setCreateTime(sdfs.format(hb.getScaleMachineVo().getCreateTime()));
				}
				if(hb.getScaleMachineVo().getLastUpdateTime()!=null){
					solr.setLastUpdateTime(sdfs.format(hb.getScaleMachineVo().getLastUpdateTime()));
				}
				solr.setCreatorId(hb.getScaleMachineVo().getCreatorId());
				solr.setDevopsId(hb.getScaleMachineVo().getDevopsId());
				solr.setBdId(hb.getScaleMachineVo().getBdId());
				if(hb.getScaleMachineVo().getPlaceTime()!=null) {
				solr.setPlaceTime(sdfs.format(hb.getScaleMachineVo().getPlaceTime()));
				}
				solr.setOrgId(hb.getScaleMachineVo().getOrgId());
				solr.setProfile(hb.getScaleMachineVo().getProfile());
				solr.setShopId(hb.getScaleMachineVo().getShopId());
				solr.setTelephone(hb.getScaleMachineVo().getTelephone());
				solr.setGeohash(hb.getScaleMachineVo().getGeoHash());
				solr.setName(hb.getScaleMachineVo().getName());
			}
			if (hb.getNet() != null) {
				solr.setNetModal(hb.getNet().getModal());
				solr.setNetSign(hb.getNet().getSign());
				solr.setNetType(hb.getNet().getType());
			}
			if (hb.getDisk() != null) {
				solr.setDiskSurplus(hb.getDisk().getSurplus());
				solr.setDiskTotal(hb.getDisk().getTotal());
			}
			if (hb.getRam() != null) {
				solr.setRamRate(hb.getRam().getRate());
			}
			 
			if (hb.getSerialPort() != null) {
				solr.setSerial2(hb.getSerialPort().getSerial2());
			}
			if (hb.getCpu() != null) {
				solr.setCpuTemperature(hb.getCpu().getTemperature());
				solr.setCpuRate(hb.getCpu().getRate());
			}
			
			
			listEs.add(solr);
		}
		try {
//			 solr = heartbeatSolrRepository.save(solr);
			heartbeatEsRepository.bulkSave(listEs);
			falg = true;
		} catch (Exception e) {
			LOG.error("heartbeat to els：{}", "批量添加心跳失败");
			LOG.error(e.getMessage(), e);
			falg = false;
		}
		  
		return falg;
	} 

	public List<Heartbeat> saveList(List<Heartbeat> heartbeats) {
		for (Heartbeat heartbeat : heartbeats) {
			heartbeat.setId(UUID.randomUUID().toString().replace("-", ""));
		}
		// return (List<Heartbeat>) heartbeatELSRepository.save(heartbeats);
		return null;
	}

	public List<Heartbeat> getHeartbeat(String machineId) {
		// return (List<Heartbeat>) heartbeatELSRepository.findByMachineId(machineId);
		return null;

	}

}
